package divestoclimb.checklist;

import divestoclimb.checklist.data.Checklist;
import divestoclimb.checklist.data.Item;
import divestoclimb.checklist.data.ItemList;
import divestoclimb.checklist.storage.DbAdapter;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class EditTemplateItems extends ListActivity
		implements View.OnCreateContextMenuListener, TouchInterceptor.DropListener, TouchInterceptor.RemoveListener {

	private Long mTemplateId;
	private ItemList mItemList;
	private boolean mInitialized = false;
	private DbAdapter mDbHelper;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		Bundle params = icicle != null? icicle: getIntent().getExtras();
		mTemplateId = params.getLong(DbAdapter.KEY_TEMPLATE_ID);

		setContentView(R.layout.edit_template);

		TouchInterceptor ti = (TouchInterceptor)getListView();
		ti.setOnCreateContextMenuListener(this);
		ti.setDropListener(this);
		ti.setRemoveListener(this);
		ti.setItemsCanFocus(true);

		mDbHelper = new DbAdapter(this);

		Button addcheck = (Button)findViewById(R.id.button_add_check);
		addcheck.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(intentEditItem(EditItem.ACTION_NEW, DbAdapter.ITEM_TYPE_CHECK, -1), 0);
			}
		});
		Button addnote = (Button)findViewById(R.id.button_add_note);
		addnote.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(intentEditItem(EditItem.ACTION_NEW, DbAdapter.ITEM_TYPE_NOTE, -1), 0);
			}
		});
		
		mDbHelper.open();
		mItemList=new ItemList(DbAdapter.ITEM_CONTAINER_TEMPLATE, mTemplateId, mDbHelper);
		Cursor c = mItemList.getCursor();
		startManagingCursor(c);

		String from[] = new String[] { DbAdapter.KEY_ITEM_TEXT };
		int to[] = new int[] { R.id.text };
		int types[] = new int[] { ItemCursorAdapter.VIEW_TYPE_DEFAULT, ItemCursorAdapter.VIEW_TYPE_DEFAULT };

		ItemCursorAdapter items = new ItemCursorAdapter(this,
				R.layout.check, R.layout.note, c, null, from, to, types,
				DbAdapter.KEY_ITEM_TYPE, true);
		setListAdapter(items);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if(! mInitialized) {
			mInitialized = true;
		} else {
			((CursorAdapter)getListView().getAdapter()).getCursor().requery();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putLong(DbAdapter.KEY_TEMPLATE_ID, mTemplateId);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.template_edit, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i;
		switch(item.getItemId()) {
		case R.id.new_checklist:
			Checklist cl = mDbHelper.createChecklistFromTemplate(mTemplateId);
			if(cl.getID() != -1) {
				i = new Intent(this, FillChecklist.class)
					.putExtra(DbAdapter.KEY_TEMPLATE_ID, cl.getID());
				startActivity(i);
			} else {
				// An error occurred creating the checklist. Odd...
			}
			break;
		case R.id.info:
			i = new Intent(this, EditTemplate.class)
				.putExtra("action", EditTemplate.ACTION_EDIT)
				.putExtra(DbAdapter.KEY_TEMPLATE_ID, mTemplateId);

			startActivityForResult(i, 0);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.template_edit_context, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch(item.getItemId()) {
		case R.id.add_check_above:
			startActivityForResult(intentEditItem(
					EditItem.ACTION_NEW, DbAdapter.ITEM_TYPE_CHECK, info.id
				), 0);
			break;
		case R.id.add_note_above:
			startActivityForResult(intentEditItem(
					EditItem.ACTION_NEW, DbAdapter.ITEM_TYPE_NOTE, info.id
				), 0);
			break;
		case R.id.rename:
			startActivityForResult(intentEditItem(
					EditItem.ACTION_EDIT, -1, info.id
				), 0);
			break;
		case R.id.delete:
			removeItem(info.position);
			break;
		}

		return super.onContextItemSelected(item);
	}

	// Interface for moving items with the keypad is to use alt-up/down
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		ListView lv = getListView();
		int position = lv.getCheckedItemPosition();
		if (position >= 0) {
			if (event.getMetaState() != 0 && event.getAction() == KeyEvent.ACTION_DOWN) {
				Item i = DbAdapter.fetchItemFromCursor((Cursor)lv.getItemAtPosition(position));
				switch (event.getKeyCode()) {
				case KeyEvent.KEYCODE_DPAD_UP:
					mItemList.add(position-1, i);
					return true;
				case KeyEvent.KEYCODE_DPAD_DOWN:
					mItemList.add(position+1, i);
					return true;
				case KeyEvent.KEYCODE_DEL:
					removeItem(position);
					return true;
				}
			}
		}

		return super.dispatchKeyEvent(event);
	}

	// Implementation of TouchInterceptor.DropListener
	public void drop(int from, int to) {
		Cursor c = (Cursor)getListView().getItemAtPosition(from);
		Item i = DbAdapter.fetchItemFromCursor(c);
		mItemList.add(to, i);
	}

	// Implementation of TouchInterceptor.RemoveListener
	public void remove(int which) {
		removeItem(which);
	}

	protected void removeItem(int position) {
		Cursor c = (Cursor)getListView().getItemAtPosition(position);
		long selected_item=c.getLong(c.getColumnIndexOrThrow(DbAdapter.KEY_ITEM_ID));
		mDbHelper.deleteTemplateItem(selected_item);
		mItemList.getCursor().requery();
	}
	
	/**
	 * Build an Intent to EditItem based on various parameters
	 * @param action
	 * @param item_type
	 * @param item
	 * @return
	 */
	protected Intent intentEditItem(int action, int item_type, long item) {
		Intent i = new Intent(this, EditItem.class)
			.putExtra("containertype", DbAdapter.ITEM_CONTAINER_TEMPLATE)
			.putExtra("containerid", mTemplateId)
			.putExtra("action", action);
		if(action == EditItem.ACTION_NEW) {
			i.putExtra(DbAdapter.KEY_ITEM_TYPE, item_type);
		}
		if(item != -1) {
			i.putExtra(DbAdapter.KEY_ITEM_ID, item);
		}
		return i;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		if (position >= 0) {
			startActivityForResult(intentEditItem(EditItem.ACTION_EDIT, -1, id), 0);
		}
	}
}